package com.fzfnn.scrapbook.exception;

import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fzfnn.scrapbook.util.R;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    // 1. 缺少参数异常
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public R handleMissingParam(MissingServletRequestParameterException ex) {
        return R.errorMsg("不能空参");
    }

    // 2. 参数类型不匹配
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public R handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
        String name = ex.getName();
        String type = ex.getRequiredType() != null ? ex.getRequiredType().getSimpleName() : "参数类型";
        return R.errorMsg("参数类型错误：" + name + " 应该是 " + type);
    }

    // 3. 空指针异常
    @ExceptionHandler(NullPointerException.class)
    public R handleNullPointer(NullPointerException ex) {
        return R.errorMsg("空指针异常：" + ex.getMessage());
    }

    // 4. 运行时异常
    @ExceptionHandler(RuntimeException.class)
    public R handleRuntimeException(RuntimeException ex) {
        ex.printStackTrace();
        return R.errorMsg("运行时异常：" + ex.getMessage());
    }

    // 5. 数据库异常
    @ExceptionHandler(SQLException.class)
    public R handleSQLException(SQLException ex) {
        ex.printStackTrace();
        return R.errorMsg("数据库异常：" + ex.getMessage());
    }

    // 6. JSON 解析失败（常见于 POST JSON 数据结构错误）
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public R handleHttpMessageNotReadable(HttpMessageNotReadableException ex) {
        Throwable cause = ex.getCause();
        String message = "请求数据格式有误，请检查 JSON 格式";
        if (cause instanceof MismatchedInputException) {
            message = "字段格式不正确，可能是缺失、类型错误或语法错误";
        }
        return R.errorMsg(message);
    }

    // 7. 通用异常兜底
    @ExceptionHandler(Exception.class)
    public R handleOther(Exception ex, HttpServletRequest request) {
        ex.printStackTrace(); // 可选：记录日志
        return R.errorMsg("系统异常，请联系管理员");
    }

    // 8.处理上传文件大小超限异常

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public R handleMaxSizeException(MaxUploadSizeExceededException ex) {
        return R.errorMsg("上传的文件大小不能超过5MB！");
    }

}
